package com.zib.vread.myapplication;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import java.util.LinkedList;
import java.util.List;

/**
 * Created by vread on 2016/8/15.
 * <p/>
 * 根据手指按下的X,Y坐标来获取我们在Listview上面点击的item
 * 手指按下的时候使用Handler和Runnable来实现一个定时器，时间为1秒，在1秒内，如果手指抬起了移除定时器，没有抬起并且手指点击在listview的item所在的区域，则表示我们长按
 * 如果我们长按了item则隐藏item,然后添加一个item的镜像在屏幕用来代替刚刚隐藏的item
 * 当我们手指在屏幕移动的时候，更新item镜像的位置，然后在根据我们移动的X,Y的坐标来获取移动到哪一个位置
 * 到listview的item过多的时候，可能一屏幕显示不完，我们手指拖动item镜像到屏幕下方，要触发listview想上滚动
 * listview交换数据，刷新界面，移除item的镜像
 */
public class DragListView extends ListView {
    //默认长按时间
    private long defaultTimeOfLong = 1000;
    //drag状态，默认false
    private boolean isDrag = false;
    //手指按下的坐标
    private int mDownX;
    private int mDownY;
    //手指移动距离
    private int moveX;
    private int moveY;
    //手指按下item的position
    private int mDragPosition;
    //手指按下的item
    private View mDragItemView = null;
    //手指按下item的镜像文件
    private Bitmap mDragBitmap;
    private ImageView mDragImageView;

    private WindowManager mWindowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
    private WindowManager.LayoutParams mWindowLayoutParams;
    //创建镜像确定位置数据
    //按下位置到控件的距离
    private int mPointOfItemTop;
    private int mPointOfItemLeft;
    //listview距离屏幕边缘的偏移量
    private int mOffsetOfTop;
    private int mOffsetOfLeft;
    //状态栏高度
    private int mStatusHeight;

    //自动滑动设定
    //listview上下滚动的限定值
    private int mDownScrollBorder;
    private int mUpScrollBorder;
    //滚动速度
    private static final int speed = 80;

    private OnChanageListener onChanageListener;

    public DragListView(Context context) {
        super(context, null);
    }

    public DragListView(Context context, AttributeSet attrs) {
        super(context, attrs, 0);
    }

    public DragListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mStatusHeight = getStatusHeight(context);
    }

    private Handler mHandler = new Handler();

    private Runnable mLongClickRunnable = new Runnable() {
        @Override
        public void run() {
            isDrag = true;
            mDragItemView.setVisibility(View.INVISIBLE);
            createDragImage(mDragBitmap, mDownX, mDownY);
        }
    };


    public void setOnChangeListener(OnChanageListener onChanageListener) {
        this.onChanageListener = onChanageListener;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mHandler.postDelayed(mLongClickRunnable, defaultTimeOfLong);

                mDownX = (int) ev.getX();
                mDownY = (int) ev.getY();

                mDragPosition = pointToPosition(mDownX, mDownY);

                if (mDragPosition == AdapterView.INVALID_POSITION) {
                    return super.dispatchTouchEvent(ev);
                }

                mDragItemView = getChildAt(mDragPosition - getFirstVisiblePosition());

                mPointOfItemTop = mDownY - mDragItemView.getTop();
                mPointOfItemLeft = mDownX - mDragItemView.getLeft();
                mOffsetOfTop = (int) (ev.getRawY() - mDownY);
                mOffsetOfLeft = (int) (ev.getRawX() - mDownX);

                mDownScrollBorder = getHeight() / 4;
                mUpScrollBorder = getHeight() * 3 / 4;

                mDragItemView.setDrawingCacheEnabled(true);
                mDragBitmap = Bitmap.createBitmap(mDragItemView.getDrawingCache());
                mDragItemView.destroyDrawingCache();
                break;
            case MotionEvent.ACTION_MOVE:
                int moveX = (int) ev.getX();
                int moveY = (int) ev.getY();
                //如果不是在item上移动的时候
                if (!isTouchInItem(mDragItemView, moveX, moveY)) {
                    mHandler.removeCallbacks(mLongClickRunnable);
                }
                break;
            case MotionEvent.ACTION_UP:
                mHandler.removeCallbacks(mLongClickRunnable);
                mHandler.removeCallbacks(mScrollRunnable);
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 判断是不是在item上移动
     *
     * @param dragView
     * @param x
     * @param y
     * @return
     */
    private boolean isTouchInItem(View dragView, int x, int y) {
        int leftOffset = dragView.getLeft();
        int topOffset = dragView.getTop();
        if (x < leftOffset || x > leftOffset + dragView.getWidth()) {
            return false;
        }
        if (y < topOffset || y > topOffset + dragView.getHeight()) {
            return false;
        }
        return true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (isDrag && mDragImageView != null) {
            switch (ev.getAction()) {
                case MotionEvent.ACTION_MOVE:
                    moveX = (int) ev.getX();
                    moveY = (int) ev.getY();
                    if (mAnimationEnd) {
                        onDragItem(moveX, moveY);
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    onStopDrag();
                    isDrag = false;
                    break;
            }
            return true;
        }
        return super.onTouchEvent(ev);
    }

    /**
     * 创建镜像
     *
     * @param bitmap
     * @param downX
     * @param downY
     */
    private void createDragImage(Bitmap bitmap, int downX, int downY) {
        mWindowLayoutParams = new WindowManager.LayoutParams();
        mWindowLayoutParams.format = PixelFormat.TRANSLUCENT;
        mWindowLayoutParams.gravity = Gravity.TOP | Gravity.LEFT;
        mWindowLayoutParams.x = downX - mOffsetOfTop + mOffsetOfLeft;
        mWindowLayoutParams.y = downY - mPointOfItemTop + mOffsetOfTop - mStatusHeight;
        mWindowLayoutParams.alpha = 0.5f;
        mWindowLayoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        mWindowLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        mWindowLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;

        mDragImageView = new ImageView(getContext());
        mDragImageView.setImageBitmap(bitmap);
        mWindowManager.addView(mDragImageView, mWindowLayoutParams);
    }

    private void removeDragImage() {
        if (mDragImageView != null) {
            mWindowManager.removeView(mDragImageView);
            mDragImageView = null;
        }
    }

    /**
     * 拖动item，在里面实现了item镜像的位置更新，item的相互交换以及GridView的自行滚动
     *
     * @param moveX
     * @param moveY
     */
    private void onDragItem(int moveX, int moveY) {
        mWindowLayoutParams.x = moveX - mPointOfItemLeft + mOffsetOfLeft;
        mWindowLayoutParams.y = moveY - mPointOfItemTop + mOffsetOfTop - mStatusHeight;
        mWindowManager.updateViewLayout(mDragImageView, mWindowLayoutParams);
        onSwapItem(moveX, moveY);
        mHandler.post(mScrollRunnable);
    }

    private Runnable mScrollRunnable = new Runnable() {

        @Override
        public void run() {
            int scrollY;
            if (moveY > mUpScrollBorder) {
                scrollY = -speed;
                mHandler.postDelayed(mScrollRunnable, 25);
            } else if (moveY < mDownScrollBorder) {
                scrollY = speed;
                mHandler.postDelayed(mScrollRunnable, 25);
            } else {
                scrollY = 0;
                mHandler.removeCallbacks(mScrollRunnable);
            }
            onSwapItem(moveX, moveY);
            View view = getChildAt(mDragPosition - getFirstVisiblePosition());
            smoothScrollToPositionFromTop(mDragPosition, view.getTop() + scrollY);
        }
    };

    /**
     * 交换item
     *
     * @param moveX
     * @param moveY
     */
    private void onSwapItem(int moveX, int moveY) {
        final int tempPosition = pointToPosition(moveX, moveY);

        if (tempPosition != mDragPosition && tempPosition != AdapterView.INVALID_POSITION && mAnimationEnd) {
            getChildAt(tempPosition - getFirstVisiblePosition()).setVisibility(View.INVISIBLE);
            getChildAt(mDragPosition - getFirstVisiblePosition()).setVisibility(View.VISIBLE);
            if (onChanageListener != null) {
                onChanageListener.onChange(mDragPosition, tempPosition);
                animateReorder(mDragPosition, tempPosition);
            }
            mDragPosition = tempPosition;
        }


    }


    private void onStopDrag() {
        getChildAt(mDragPosition - getFirstVisiblePosition()).setVisibility(View.VISIBLE);
        removeDragImage();
    }

    private static int getStatusHeight(Context context) {
        int statusHeight = 0;
        Rect localRect = new Rect();
        ((Activity) context).getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect);
        statusHeight = localRect.top;
        if (0 == statusHeight) {
            Class<?> localClass;
            try {
                localClass = Class.forName("com.android.internal.R$dimen");
                Object localObject = localClass.newInstance();
                int i5 = Integer.parseInt(localClass.getField("status_bar_height").get(localObject).toString());
                statusHeight = context.getResources().getDimensionPixelSize(i5);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return statusHeight;
    }


    public interface OnChanageListener {
        public void onChange(int form, int to);
    }


    private void animateReorder(final int oldPosition, final int newPosition) {
        boolean isForward = newPosition > oldPosition;
        List<Animator> resultList = new LinkedList<Animator>();
        if (isForward) {
            View view = getChildAt(oldPosition - getFirstVisiblePosition());
            resultList.add(createTranslationAnimations(view,
                    0, 0, view.getHeight(), 0));
        } else {
            View view = getChildAt(oldPosition - getFirstVisiblePosition());
            resultList.add(createTranslationAnimations(view,
                    0, 0, -view.getHeight(), 0));
        }

        AnimatorSet resultSet = new AnimatorSet();
        resultSet.playTogether(resultList);
        resultSet.setDuration(100);
        resultSet.setInterpolator(new AccelerateDecelerateInterpolator());
        resultSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                mAnimationEnd = false;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mAnimationEnd = true;
            }
        });
        resultSet.start();
    }

    private AnimatorSet createTranslationAnimations(View view, float startX,
                                                    float endX, float startY, float endY) {
        ObjectAnimator animX = ObjectAnimator.ofFloat(view, "translationX",
                startX, endX);
        ObjectAnimator animY = ObjectAnimator.ofFloat(view, "translationY",
                startY, endY);
        AnimatorSet animSetXY = new AnimatorSet();
        animSetXY.playTogether(animX, animY);
        return animSetXY;
    }

    private boolean mAnimationEnd = true;
}
